
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jose
 */
public class Modelo {
    
    private String path;
    private String currentSerie;
    private int currentChapter;
    private int currentSeason;
    private boolean lastChapter;
    private boolean nextChapter;
    private boolean lastSeason;
    private boolean nextSeason;
    private VentanaPrincipal vPrincipal;
    private File config;
    
    public Modelo(String nameConfig) {
        currentSerie=null;
        currentChapter=0;
        currentSeason=0;
        config = new File(nameConfig);
        leerConfig();
        if (path==null){
            vPrincipal = new VentanaPrincipal(this,false);
        }else{
            vPrincipal = new VentanaPrincipal(this,true);
            ImageIcon imagen = new ImageIcon(path + "\\" + currentSerie + "\\" + currentSerie + ".jpg");
            String [] series = getSeries();
            vPrincipal.setAll(series,imagen,series[currentSeason],Integer.toString(currentChapter), currentSerie);
        }
        vPrincipal.setVisible(true);
    }
        
    private String leerPath(){
        String p = null;
        if(!config.exists()){
            try {
                config.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(Modelo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else{
            try {
                BufferedReader br = new BufferedReader(new FileReader(config));
                String linea;
                
                do{
                    linea=br.readLine();
                }while(linea != null && !linea.equals("#path"));
                
                if( (linea=br.readLine()) != null ){
                    p=linea;
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Modelo.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Modelo.class.getName()).log(Level.SEVERE, null, ex);
            } 
        }
        return p;
    }
    
    private boolean leerCurrentSerie(){
        try {
           BufferedReader br = new BufferedReader(new FileReader(config));
           String linea;

           do{
               linea=br.readLine();
           }while(linea != null && !linea.equals("#currentSerie"));

           if( (linea=br.readLine()) != null ){
               if(!linea.equals("#Series")){
                   currentSerie=linea;
                   return true;
               }
           }
        } catch (FileNotFoundException ex) {
           Logger.getLogger(Modelo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
           Logger.getLogger(Modelo.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }
    
    private int[] buscarSerie(String serie){
        int [] datos = new int [2];
        datos[0] = 0;
        datos[1] = 0;
        try {
           BufferedReader br = new BufferedReader(new FileReader(config));
           String linea;

           do{
               linea=br.readLine();
               System.out.println("1. " + linea);
           }while(linea != null && !linea.equals("#Series"));

           while( (linea=br.readLine()) != null ){
               System.out.println("2. " + linea);
               if(linea.contains(serie)){
                   String [] info = linea.split(":");
                   datos[0] = Integer.parseInt(info[1]);
                   datos[1] = Integer.parseInt(info[2]);
               }
           }
        } catch (FileNotFoundException ex) {
           Logger.getLogger(Modelo.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
           Logger.getLogger(Modelo.class.getName()).log(Level.SEVERE, null, ex);
        }
        return datos;
    }
    
    private void leerConfig(){
        path = leerPath();
        if(path!=null){
            if(leerCurrentSerie()){
                System.out.println(currentSerie);
                int [] datos = buscarSerie(currentSerie);
                currentSeason = datos[0];
                currentChapter = datos[1];
                System.out.println("season " + currentSeason + " chapter " + currentChapter);
            }
        }
    }
 
    private void escribirConfig(){
        PrintWriter pw = null;
        BufferedReader br = null;
        File auxFile = new File("aux_" + config.getName());
        String linea;
        try
        {
            if(!auxFile.exists()){
                auxFile.createNewFile();
            }
            pw = new PrintWriter(new FileWriter(auxFile));
            br = new BufferedReader(new FileReader(config));
 
            pw.println("#path");
            pw.println(path);
            pw.println("#currentSerie");
            pw.println(currentSerie);
            pw.println("#Series");
            
            do{
               linea=br.readLine();
            }while(linea != null && !linea.equals("#Series"));
            
            if(linea==null){
                pw.println(currentSerie + ":" + currentSeason + ":" + currentChapter);  
            }
            while( (linea=br.readLine())!=null){
                if(linea.contains(currentSerie)){
                    pw.println(currentSerie + ":" + currentSeason + ":" + currentChapter);  
                }else{
                    pw.println(linea);
                }
            }  
            config.delete();
            auxFile.renameTo(config);
            //config = auxFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public String[] getSeries(){
        File directorio = new File(path);
        FilenameFilter fnf = new FilenameFilter() {

            @Override
            public boolean accept(File file, String string) {
                File f = new File(file,string);
                return f.isDirectory();
            }
        };
        String [] series = directorio.list(fnf);
        return series;
    }
    
    public String[] getSeries(String path){
        setPath(path);
        return getSeries();
    }
    
    private void setPath(String path){
        this.path = path;
        escribirConfig();
//        FileWriter fichero = null;
//        PrintWriter pw = null;
//        try
//        {
//            fichero = new FileWriter("config.txt");
//            pw = new PrintWriter(fichero);
// 
//            pw.println(path);
// 
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//           try {
//              if (null != fichero)
//                fichero.close();
//           } catch (Exception e2) {
//              e2.printStackTrace();
//           }
//        }
    }
    
    public void setSerie (String serie){
        int [] datos = buscarSerie(serie);
        currentSerie = serie;
        currentSeason = datos[0];
        currentChapter = datos[1];
        System.out.println("season " + currentSeason + " chapter " + currentChapter);
        ImageIcon imagen = new ImageIcon(path + "\\" + serie + "\\" + serie + ".jpg");
        vPrincipal.setBackgroundImage(imagen);
        vPrincipal.setSeason(Integer.toString(currentSeason));
        vPrincipal.setChapter(Integer.toString(currentChapter));
    }
    
    public void reproducir(){
        try {
            Process p = Runtime.getRuntime().exec("cmd /C " + path + "\\" + currentSerie + "\\Temporada 2\\The Wire 2x01 - Baja Mar.avi");
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while((line = in.readLine())!=null){
                System.out.println(line);
            }
        } catch (IOException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public boolean isLastChapter(){
        return lastChapter;
    }
    
    public boolean isNextChapter(){
        return nextChapter;
    }
    
    public boolean isLastSeason(){
        return lastSeason;
    }
    
    public boolean isNextSeason(){
        return nextSeason;
    }
    
    public void nextChapter(){
        currentChapter++;
        nextChapter=false;//TODO mirar si existe capitulo
        escribirConfig();
    }
    
    public void previousChapter(){
        currentChapter--;
    }
    
    public void nextSeason(){
        currentSeason++;
        currentChapter=0;
    }
    
    public void previousSeason(){
        currentSeason--;
        currentChapter=0;
    }
}
